<template>
    <div class="game-item" v-for="(item, index) in categoryList" :key="item.id"
        :ref="(el) => setGameItemRef(el, index)">
        <!-- 左侧文字和人数-->
        <div class="flex items-center  mb-5 py-10 px-15">
            <img :src="getIcon(item.gameType)" alt="" class="w-20 mr-3 opacity-50">
            <div class="color-#c9ccd7">{{ item.name }}</div>
            <div class="people">
                <img src="/imgs/people.png" alt="" class="w-13">
                <div class="color-#9CFF27 pl-5 text-12">{{ item.num }}</div>
            </div>
        </div>
        <!-- 右侧按钮 -->
        <div class="flex items-center absolute right-15 top-0">
            <div class="more color-#a0a4b0" @click="handleMoreClick(item)">
                更多<van-icon name="arrow" color="#a0a4b0" />
            </div>
            <img src="/imgs/pre.png" alt="" class=" w-23 mx-10" @click="prev(index)"
                :class="{ 'opacity-200': currentIndexList[index] === 0 }">
            <img :src="nextImg" alt="" class=" w-23" @click="next(index, item.list.length)"
                :class="{ 'opacity-50': currentIndexList[index] + 3 >= item.list.length + 1 }">
        </div>
        <!-- 轮播图 -->
        <div class="swiper-box">
            <div class="image-window">
                <div class="image-track" :style="{
                    transform: `translateX(-${currentIndexList[index] * (imageWidth + gap)}px)`
                }">
                    <div v-for="(v, i) in item.list" :key="i" class="item-img" @click="handleGameClick(v)">
                        <!-- 背景图 -->
                        <!-- <img src="/game/mask_green.png" alt="" class="bg-img" /> -->
                        <!-- 游戏图（带遮罩） -->
                        <img :src="v.icon" alt="" class="game-img" />
                        <!-- 热门标志 -->
                        <img src="/imgs/hot_logo.png" alt="" v-if="v.hot" class="hot-logo">
                        <div class="collect" @click.stop="toCollect(v)">
                            <img :src="v.active ? '/imgs/collect.png' : '/imgs/collect_un.png'" alt=""
                                class="w-25 mr-3" />
                        </div>
                        <!-- <div class="info">
                            <div class="color-#d1c3fd font-bold">PG</div>
                            <div class="color-#f9b2ef text-10 warp">hhhhhhh</div>
                        </div> -->
                    </div>
                    <!-- 新增"更多"卡片 -->
                    <div class="item-img more-card" @click="handleMoreClick(item)">
                        <img src="/game/mask_more.png" alt="" class="bg-img" />
                        <div class="more-content">
                            <div class="font-bold text-18">更多</div>
                            <span class="color-#7771dd">查看所有</span>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>
<script setup>
import { ref, watch } from 'vue'
import { saveCollectApi, gameUrlApi } from '@/api/home'
import nextImg from './public/imgs/next.png'
const { t } = useI18n()
const userStore = useUserStore()
// import type { WebIframe } from '@/api/model/home'
import { getIcon } from '@/utils/icon'
const props = defineProps({
    categoryList: {
        type: Array,
        required: true,
        default: () => []
    },
})
const emits = defineEmits(['gameClick', 'updateCollect']) // 定义事件
// 每组轮播独立的 currentIndex
const currentIndexList = ref([])
const curCollectObj = ref({})

watch(
    () => props.categoryList,
    (newList) => {
        currentIndexList.value = newList.map(() => 0)
    },
    { immediate: true }
)
// 每张图宽度和间距（必须与 CSS 保持一致）
const imageWidth = 100
const gap = 20

const prev = (index) => {
    if (currentIndexList.value[index] > 0) {
        currentIndexList.value[index]--
    }
}

const next = (index, total) => {
    // +1 是为了包含"更多"卡片
    if (currentIndexList.value[index] + 3 < total + 1) {
        currentIndexList.value[index]++
    }
}
const router = useRouter()
const configStore = useConfigStore()
const handleMoreClick = (item) => {
    router.push({
        path: '/home/search',
    });
    let params = { type: item.gameType, name: item.name }
    configStore.setMoreParams(params)
};
// 进入游戏
const handleGameClick = (item) => {
    if (!userStore.isLogin) return router.push('/login')
   gameUrlApi({ gameId: item.gameId }).then(res => {
        emits('gameClick', {
            gold: 999.99,
            name: item.name,
            webViewUrl: res
        })
   })
}
const gameItemRefs = ref([])

const setGameItemRef = (el, index) => {
    gameItemRefs.value[index] = el
}
const toCollect = async (v) => {
    if (!userStore.isLogin) return router.push('/login')
    try {
        let res = await saveCollectApi({ gameId: v.gameId, add: !v.active })
        v.active = !v.active
        emits('updateCollect', v)
        showSuccessToast(v.active?'收藏成功！':'取消收藏成功！')
    } catch (error) {
        showFailToast('收藏失败！')
    }

}
defineExpose({ gameItemRefs }) 
</script>

<style scoped>
.game-item {
    background: url('/imgs/item_bg.png') no-repeat;
    background-size: 100% 100%;
    position: relative;
    overflow: hidden;
    /* margin-top: 10px; */
    padding-bottom: 10px;
}

.people {
    background: url('/imgs/people_bg.png') no-repeat;
    background-size: 100% 100%;
    padding: 2px 6px;
    margin-left: 10px;
    display: flex;
    align-items: center;
}

.collect {
    position: absolute;
    z-index: 3;
    left: 2px;
    bottom: 5px;
    display: flex;
    align-items: center;
}

.more {
    /* background: url('/imgs/grey_bg.png') no-repeat;
    background-size: 100% 100%; */
    background: #2d2f39;
    border-radius: 6px;
    padding: 2px 3px 2px 10px;
    font-size: 12px;
}

.swiper-box {
    display: flex;
    justify-content: center;
    align-items: center;
    /* overflow: hidden; */
    padding-bottom: 10px;
}

.image-window {
    width: calc(100px * 3 + 20px * 2);
    /* 可视范围内最多3张图，间距2个gap */
    /* overflow: auto; */
}

/* 新增：热门标志图标 */
.hot-logo {
    position: absolute;
    top: -8px;
    /* 向上偏移 */
    left: -3px;
    /* 向左偏移 */
    width: 50px;
    /* 自行根据设计调整 */
    z-index: 2;
    pointer-events: none;
    /* 不影响点击 */
}

.image-track {
    display: flex;
    /* 横向排列靠这个 */
    gap: 20px;
    transition: transform 0.4s ease;
}

.info {
    width: 40%;
    display: flex;
    align-items: center;
    color: #d3c7fd;
    font-size: 12px;
    position: absolute;
    z-index: 3;
    bottom: 0;
    right: 0;
}

.info .warp {
    width: 60%;
    line-height: 6px;
    word-wrap: break-word;
    /* 允许长单词换行 */
    white-space: normal;
    /* 覆盖默认的 nowrap */
}

.item-img {
    width: 100px;
    height: 140px;
    position: relative;
    border-radius: 8px;
    /* overflow: hidden; */
    flex-shrink: 0;
    /* 防止被压缩 */
}

.bg-img {
    position: absolute;
    inset: 0;
    width: 100%;
    height: 100%;
    object-fit: cover;
    z-index: 0;
    border-radius: 8px;
}

.game-img {
    position: absolute;
    inset: 0;
    width: 100%;
    height: 100%;
    object-fit: cover;
    z-index: 1;
    border-radius: 8px;
    /* mask-image: linear-gradient(to bottom, black 35%, transparent 100%);
    -webkit-mask-image: linear-gradient(to bottom, black 35%, transparent 100%);
    mask-size: 100% 100%;
    -webkit-mask-size: 100% 100%; */
}

.more-card {
    display: flex;
    justify-content: center;
    align-items: center;
    cursor: pointer;
}

.more-content {
    display: flex;
    flex-direction: column;
    align-items: center;
    color: white;
    z-index: 2;
}

.more-content span {
    margin-top: 8px;
    font-size: 12px;
}
</style>
